MathJax = {
    tex: {
        packages: { '[+]': ['noerrors'] },
        inlineMath: [['$', '$'], ['\\(', '\\)'], ['\\[', '\\]'], ['\begin{equation}', '\end{equation}']],
        displayMath: [['$$', '$$'], ['\\[', '\\]']],
        processEscapes: true,
        processEnvironments: true,
    },
    options: {
        skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre'],
        ignoreHtmlClass: 'code-wrapper',
    },
    startup: {
        typeset: false,
        ready: function () {
            MathJax.startup.defaultReady();
            MathJax.startup.promise.then(() => {
                console.log('MathJax initialized');
            }).catch((err) => {
                console.error('MathJax initialization failed:', err);
            });
        }
    },
    loader: {
        load: ['[tex]/noerrors']
    }
};

function ToLatex(inputString) {
    const latexFormulaRegex = /\$\$(.*?)\$\$|\$(.*?)\$|\\\((.*?)\\\)|\\\[(.*?)\\\]/g;
    let latexFormulas = [];
    
    inputString = inputString.replace(/(\\\[|\\begin{equation})[\s\S]*?(\\]|\\end{equation})/g, function (match) {
        return match.replace(/\s*\n\s*/g, ' ');
    })
    
    inputString = inputString.replace(latexFormulaRegex, (match, p1, p2) => {
        latexFormulas.push(match);
        return `{latexFormula${latexFormulas.length - 1}}`;
    });
    
    const converter = new showdown.Converter();
    inputString = converter.makeHtml(inputString)

    inputString = inputString.replace(/{latexFormula(\d+)}/g, (match, index) => {
        return latexFormulas[index];
    });
    
    return inputString;
}
